import { defineStore } from 'pinia'

import { reqLogin, reqUserInfo } from '@/api/user'
import type {
  loginFormData,
  loginResponseData,
  //   logoutResponseData,
  userResponseDate,
} from '@/api/user/type'

import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'

import { constantRoute, asnycRoute, anyRoute } from '@/router/routers'

import type { UserState } from './types/type'
import { deepClone } from '@/utils/handleData'
import { filterAsyncRoute } from '@/utils/router'

import router from '@/router'

const myUserInfo_init = Object.freeze({
  avatar: '',
  name: '',
  roles: [],
  buttons: [],
  routes: [],
})

const useUserStore = defineStore('User', {
  state(): UserState {
    return {
      token: GET_TOKEN(),
      menuRouters: constantRoute,
      myUserInfo: { ...myUserInfo_init },
    }
  },
  actions: {
    async userLogin(loginForm: loginFormData) {
      //   console.log(data)
      const result: loginResponseData = await reqLogin(loginForm)

      if (result.code == 200) {
        this.token = result.data
        SET_TOKEN(result.data)
        return true
      } else {
        // ElMessage({
        //   type: 'error',
        //   message,
        // })
        return Promise.reject(new Error(result.data))
      }
    },

    async userLogout() {
      //   const result: logoutResponseData = await reqLogout()
      //   if (result.code == 200) {
      this.token = ''
      REMOVE_TOKEN()
      this.myUserInfo = { ...myUserInfo_init }

      console.log(this.myUserInfo)

      return true
      //   } else {
      //     return Promise.reject(new Error(result.message))
      //   }
    },
    async getUserInfo() {
      const result: userResponseDate = await reqUserInfo()
      if (result.code == 200) {
        this.myUserInfo = result.data
        // SET_TOKEN(result.data.token)
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(
          deepClone(asnycRoute),
          result.data.routes,
        )
        console.log(userAsyncRoute)

        //菜单需要的数据整理完毕
        this.menuRouters = [...constantRoute, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })

        return true
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
